/************************************
 * created by Tonk (tonk@ctonk.com) *
 ************************************/

// board.cpp

#include "definitions.h"
#include <fstream>
#include <list>
#include <string>
#include "note.h"
#include "board.h"
#include "stringutil.h"
#include "logs.h"

int Board::numBoards = 0;

Board::Board() {
	setNumber( 0 );
	setLevel( 0 );
	numBoards++;
}

Board::Board( Board& it ) {
	setNumber( it.getNumber() );
	setLevel( it.getLevel() );
	setName( it.getName() );
	for ( std::list< Note* >::iterator n_it = it.getNotes().begin(); n_it != it.getNotes().end(); n_it++ )
		*(addNote()) = *(*n_it);
}

Board::Board( int number, int level, const std::string& name ) {
	setNumber( number );
	setLevel( level );
	setName( name );
}

Board::~Board() {
	Note* note = 0;

	for ( std::list< Note* >::iterator it = getNotes().begin(); it != getNotes().end(); it++ ) {
		note = (*it);
		dropNote( note );
		delete note;
		note = 0;
	}

	numBoards--;
}

void Board::setNumber( int number ) {
	_number = ( number > 0 ) ? number : 0;
	return;
}

int Board::getNumber() {
	return _number;
}

void Board::setLevel( int level ) {
	_level = ( level > 0 ) ? level : 0;
	return;
}

int Board::getLevel() {
	return _level;
}

void Board::setName( std::string name ) {
	_name = name;
	_file = "system/boards/" + getName() + ".board";
	return;
}

std::string Board::getName() {
	return _name;
}

std::string Board::getFile() {
	return _file;
}

std::list< Note* >& Board::getNotes() {
	return _notes;
}

Note* Board::addNote() {
	Note* note = new Note;
	getNotes().push_back( note );
	return note;
}

void Board::dropNote( Note* note ) {
	getNotes().remove( note );
	return;
}

void Board::load() {
	char temp[100000];
	std::ifstream read( getFile().c_str() );

	if ( read.fail() ) {
		std::string message;
		message << "Could not open \"" << getFile() << "\" for reading.";
		std::cerr << message << '\n';
		log( SERVER, message );
		return;
	}

	while ( read.peek() != EOF ) {
		read.getline( temp, 100000 );
		if ( strcmp( temp, "**NOTE" ) == 0 ) {
			addNote()->load( read );
			continue;
		}
	}

	read.close();

	return;
}

void Board::save() {
	std::ofstream write( getFile().c_str() );

	// Save notes in sequence...
	for ( int i = 0; i < Note::noteIndex; i++ )
		for ( std::list< Note* >::iterator it = getNotes().begin(); it != getNotes().end(); it++ )
			if ( (*it)->getId() == i )
				(*it)->save( write );

	write.close();
	write.clear();

	return;
}

void Board::initialize( int number, int level, std::string name ) {
	setNumber( number );
	setLevel( level );
	setName( name );
	return;
}	
